package commands;

import java.net.InetSocketAddress;
import java.net.Socket;
import main.InputHandler;
import util.*;

public class ConnectCommand extends Command {
	public static String name = "connect";
	public static String help = "Name: connect \n>connect {str:form('00#.00#.00#.00#')} {int:form('0####')} {str}\n>connect (ip address) (port #) (user name)\n" +
			">Command to connect to a certain ip, on a selected port with a selected name.";
	public static ConnectionData socket;
	
	public static boolean test(InputHandler handler, StringList words){
		if(StringChecker.testWord(words, 0, "connect")){
			if(StringChecker.testFormat(words, 1, "00#.00#.00#.00#")){
				if(StringChecker.testFormat(words, 2, "0####")){
					if(words.size() > 3){
						if(socket == null){
							try{
								Socket temp = new Socket();
								temp.connect(new InetSocketAddress(words.get(1), Integer.parseInt(words.get(2))), 1000);
								socket = new ConnectionData(temp);
								socket.write(words.get(3));
								handler.terminal.write("Connect sucess");
								return true;
							}catch (Exception e){
								handler.terminal.write("Connection error encountered");
								return true;
							}
						}else{
							handler.terminal.write("Already connected to another computer");
							return true;
						}
					}
					handler.terminal.write("No name specified");
					return true;
				}
				handler.terminal.write("Connect sucess");
				return true;
			}
		}
		return false;
	}
}
